package second.binarytree.solution05;

import java.util.LinkedList;

public class Solution05_116 {
    public Node2 connect1(Node2 root) {
        if (root == null) return null;
        LinkedList<Node2> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Node2 pre = null;
            while (size-- > 0) {
                Node2 node2 = queue.removeFirst();
                if (pre != null) {
                    pre.next = node2;
                }
                pre = node2;
                if (node2.left != null) queue.add(node2.left);
                if (node2.right != null) queue.add(node2.right);
            }
        }
        return root;
    }

    public Node2 connect(Node2 root) {
        if (root == null) return null;
        connectNode(root);
        return root;
    }

    public void connectNode(Node2 root) {
        if (root == null) return;

        if (root.left != null) {
            root.left.next = root.right;
        }
        if (root.right != null) {
            if (root.next != null) {
                root.right.next = root.next.left;
            }
        }
        connectNode(root.left);
        connectNode(root.right);
    }
}

class Node2 {
    public int val;
    public Node2 left;
    public Node2 right;
    public Node2 next;

    public Node2() {
    }

    public Node2(int _val) {
        val = _val;
    }

    public Node2(int _val, Node2 _left, Node2 _right, Node2 _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
}
